package com.zq.myrobot.activity;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zq.myrobot.R;
import com.zq.myrobot.map.LocationApplication;
import com.zq.myrobot.util.PreferenceUtils;
import com.zq.myrobot.util.Util;
import com.zq.myrobot.widget.RoundedCornerImageView;

public class MainActivity extends Activity {
	private LocationClient mLocationClient;
	// private TextView LocationResult;
	RoundedCornerImageView image_touxiang;
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	private String tempcoor = "gcj02";

	public static String mAppid;
	public static QQAuth mQQAuth;
	private UserInfo mInfo;
	private Tencent mTencent;
	TextView tv_name;
	private final String APP_ID = "900030292";// 在这里换成自己的APP_ID，在QQ互联上申请！

	private FinalBitmap fb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		image_touxiang = (RoundedCornerImageView) findViewById(R.id.image_touxiang);
		mLocationClient = ((LocationApplication) getApplication()).mLocationClient;
		tv_name = (TextView) findViewById(R.id.tv_name);
		// LocationResult = (TextView) findViewById(R.id.LocationResult);
		// ((LocationApplication) getApplication()).mLocationResult =
		// LocationResult;
		InitLocation();
		mLocationClient.start();
		fb = FinalBitmap.create(this);// 初始化FinalBitmap模块
		String imageString = PreferenceUtils.getPrefString(MainActivity.this,
				PreferenceUtils.USER_IMAGE, "");
		String userStr = PreferenceUtils.getPrefString(MainActivity.this,
				PreferenceUtils.USER_NAME, "");
		fb.display(image_touxiang, imageString);
		if (TextUtils.isEmpty(userStr)) {
			tv_name.setText("QQ授权登录");
		} else {
			tv_name.setText(userStr);
		}

		image_touxiang.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("unused")
			@Override
			public void onClick(View v) {
				onClickLogin();
				Context context = v.getContext();
				Class<?> cls = null;
				if (cls != null) {
					Intent intent = new Intent(context, cls);
					context.startActivity(intent);
				}

			}
		});

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		mLocationClient.stop();
		super.onStop();
	}

	@Override
	protected void onStart() {
		final Context context = MainActivity.this;
		final Context ctxContext = context.getApplicationContext();
		mAppid = APP_ID;
		mQQAuth = QQAuth.createInstance(mAppid, ctxContext);
		mTencent = Tencent.createInstance(mAppid, MainActivity.this);
		super.onStart();
	}

	private void InitLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(tempMode);// ���ö�λģʽ
		option.setCoorType(tempcoor);// ���صĶ�λ����ǰٶȾ�γ�ȣ�Ĭ��ֵgcj02
		int span = 1000;
		option.setScanSpan(span);// ���÷���λ����ļ��ʱ��Ϊ5000ms
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
	}

	private void updateUserInfo() {
		if (mQQAuth != null && mQQAuth.isSessionValid()) {
			IUiListener listener = new IUiListener() {

				@Override
				public void onError(UiError e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onComplete(final Object response) {
					System.out.println("------------------"
							+ response.toString());
					Message msg = new Message();
					msg.obj = response;
					msg.what = 0;
					mHandler.sendMessage(msg);
				}

				@Override
				public void onCancel() {
				}
			};
			mInfo = new UserInfo(this, mQQAuth.getQQToken());
			mInfo.getUserInfo(listener);

		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				JSONObject response = (JSONObject) msg.obj;
				if (response.has("nickname")) {
					try {
						String userNameStr = response.getString("nickname");
						String imageStr = response.getString("figureurl_qq_2");
						PreferenceUtils.setPrefString(MainActivity.this,
								PreferenceUtils.USER_NAME, userNameStr);
						PreferenceUtils.setPrefString(MainActivity.this,
								PreferenceUtils.USER_IMAGE, imageStr);
						tv_name.setText(userNameStr);
						fb.display(image_touxiang, imageStr);
						Intent intent = new Intent(MainActivity.this,
								ChatActivity.class);
						startActivity(intent);
						finish();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				// } else if (msg.what == 1) {
				// Bitmap bitmap = (Bitmap) msg.obj;
				// image_touxiang.setImageBitmap(bitmap);
				// // mUserLogo.setImageBitmap(bitmap);
				// // mUserLogo.setVisibility(android.view.View.VISIBLE);
				// Intent intent = new
				// Intent(MainActivity.this,MainActivity.class);
				// startActivity(intent);
			}
		}

	};

	private void onClickLogin() {
		if (!mQQAuth.isSessionValid()) {
			IUiListener listener = new BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					updateUserInfo();
				}
			};
			mQQAuth.login(this, "all", listener);
			mTencent.login(this, "all", listener);
		} else {
			mQQAuth.logout(this);
			updateUserInfo();
		}
	}

	public static boolean ready(Context context) {
		if (mQQAuth == null) {
			return false;
		}
		boolean ready = mQQAuth.isSessionValid()
				&& mQQAuth.getQQToken().getOpenId() != null;
		if (!ready)
			Toast.makeText(context, "login and get openId first, please!",
					Toast.LENGTH_SHORT).show();
		return ready;
	}

	private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(Object response) {
			// Util.showResultDialog(MainActivity.this, response.toString(),
			// "登录成功");
			doComplete((JSONObject) response);
		}

		protected void doComplete(JSONObject values) {

		}

		@Override
		public void onError(UiError e) {
		}

		@Override
		public void onCancel() {
			Util.toastMessage(MainActivity.this, "onCancel: ");
			Util.dismissDialog();
		}
	}

}
